<?php

namespace Common\Model;

use Think\Model;

/**
 * 用户申请成为团体管理员的关联模型
 */
class ApplyModel extends Model {

    const TO_MANAGER = 1;   // 申请类型：管理员
    const TO_SUPER = 2;     // 申请类型：超级管理员
    const TO_BYE = -1;      // 申请类型：辞职

    const REJECTED = -1;    // 申请状态：已拒绝
    const PASSED = 1;       // 申请状态：已通过
    const WAITING = 0;      // 申请状态：等待中

    /**
     * 添加团体管理员申请记录
     * @param $uid
     * @param $bid
     * @param $type
     * @param $desc
     * @return mixed
     */
    public static function addData($uid, $bid, $type, $desc){
        $data = [
            'uid' => $uid,
            'bid' => $bid,
            'type' => $type,
            'desc' => $desc,
            'create' => time()
        ];
        return M('Apply')->add($data);
    }

    /**
     * 更新申请记录的数据
     * @param $aid
     * @param $data
     * @return bool
     */
    public static function update($aid, $data){
        return M('Apply')->where(['id' => $aid])->save($data);
    }

    /**
     * 分页获取团体管理员申请列表
     * @param $bid
     * @param $p
     * @param $pcount
     * @return array
     */
    public static function getApplyList($bid, $p, $pcount){
        $count = M('Apply')->where(['bid' => $bid])->count();
        $list = $count ? M()->table(['wo_apply' => 'a', 'wo_user' => 'u'])->where(['a.bid' => $bid])->where('a.uid = u.id')->field('a.*,u.nick')->order('a.status = '.self::WAITING.' desc,a.`create` desc')->page($p.','.$pcount)->select() : array();
        return [
            'count' => $count,
            'list' => $list
        ];
    }

    /**
     * 获取申请记录信息
     * @param $aid
     * @return mixed
     */
    public static function getApplyById($aid){
        return M('Apply')->find($aid);
    }

    /**
     * 处理申请记录
     * @param $uid
     * @param $apply
     * @param $status
     * @param $content
     * @return bool
     */
    public static function dealApply($uid, $apply, $status, $content){
        // 如果成功，需要更新管理员数据
        $applyData = [
            'mid' => $uid,
            'reply' => $content,
            'end' => time(),
            'status' => $status
        ];
        $model = M();
        $model->startTrans();
        // 先更新申请数据
        if(!self::update($apply['id'], $applyData)){
            $model->rollback();
            return false;
        }
        // 然后通知申请人，处理结果
        $tmpArr = [
            -1 => '辞职',
            1 => '管理员',
            2 => '超级管理员'
        ];
        $msg = '您向<a href="//bbs.wooo.wang/org/'.$apply['bid'].'">'.BbsModel::getBbsById($apply['bid'], false)['name'].'</a>社区提交的'.$tmpArr[$apply['type']].'申请已被管理员'.($status == self::PASSED ? '<strong class="green">通过</strong>' : '<strong class="red">拒绝</strong>').'，并回复：'.$content;
        $msgData = [
            'sid' => $uid,
            'gid' => $apply['uid'],
            'content' => $msg,
            'create' => time()
        ];
        if(!MsgModel::addData($msgData)){
            $model->rollback();
            return false;
        }
        // 如果通过申请，则需要更新用户团体关联表数据，和更新管理员缓存
        if($status == self::PASSED){
            $cancelData = [
                'end' => time(),
                'status' => UserOrgModel::DELTEL
            ];
            if($apply['type'] == self::TO_MANAGER){     // 直接上任
                if(!UserOrgModel::addData($apply['uid'], $apply['bid'], false)){
                    $model->rollback();
                    return false;
                }
            }else if($apply['type'] == self::TO_SUPER){   // 先卸任，然后上任
                if(!UserOrgModel::updateUserOrg($apply['uid'], $apply['bid'], $cancelData) || !UserOrgModel::addData($apply['uid'], $apply['bid'])){
                    $model->rollback();
                    return false;
                }
            }else if($apply['type'] == self::TO_BYE){   // 卸任
                if(!UserOrgModel::updateUserOrg($apply['uid'], $apply['bid'], $cancelData)){
                    $model->rollback();
                    return false;
                }
            }else{
                $model->rollback();
                return false;
            }
        }
        $model->commit();
        return true;
    }

}